const roomDeatil = require("./roomDetail.js")
module.exports = {
  //退出房间
    async del({ctx,conn}){
      try{
        const leaveUser = await ctx.model.RoomDetail.findOne({where:{ws_key:conn.key}})
        if(leaveUser){
          await roomDeatil.del({roomDeatilID:leaveUser.id,roomMsg:leaveUser,ctx});
          let {people,roomDeatilList,currentUser} = await this.be_left({clientData:leaveUser,ctx});
          currentUser = leaveUser;
          return {people,roomDeatilList,currentUser};
        }else{
          return null;
        }
      }catch(e){
        console.log(e)
      } 
    },
    //返回查询当前还剩下那些人,并且返回剩下key的数组
    async be_left({clientData,ctx}){
      let roomDeatilList = await ctx.model.RoomDetail.findAll({where:{room_id:clientData.room_id}});
      let people = [];
      for(let i=0;i<roomDeatilList.length;i++){
        people.push(roomDeatilList[i].ws_key)
        roomDeatilList[i].setDataValue('num',i+1)
      }
      let currentUser = roomDeatilList.find(x=>x.user_id===clientData.user_id);
      return {people,roomDeatilList,currentUser}
    },
    //用户第一次进入房间，更新key
    async firstConn({app,conn,clientData}){
      await app.model.RoomDetail.update({ws_key:conn.key,has_img:true},{where:{user_id:clientData.user_id,room_id:clientData.room_id}});
      return await this.be_left({clientData,ctx:app});
    },
    //开始游戏
    async startGame({conn,ctx,clientData}){
      let {people,roomDeatilList,currentUser} =await this.be_left({clientData,ctx});
      let role_arr = [];
      for(let item in clientData.room_role){
        for(let i=0;i<clientData.room_role[item];i++){
          role_arr.push(item);
        }
      }
      role_arr.sort(()=>{return Math.random()-0.5});
      role_arr.forEach(async (x,i)=>{
        roomDeatilList[i].role = x;
        await ctx.model.RoomDetail.update({role:x},{where:{id:roomDeatilList[i].id}})
      })
      return {people,roomDeatilList,currentUser};
    },
    async getRoomOwern({conn,ctx,clientData}){
      return await ctx.model.RoomDetail.findOne({where:{room_id:clientData.homie[0].room_id,is_owners:true}})
    }
}